const path = require("path");
const express = require("express");
const fileUpload = require("express-fileupload"); //文件上传
const cors = require('cors');
const app = express();

require("dotenv").config(); //读取.env文件
require("./common/mongodb"); //数据库连接
require("./schedule/index"); //任务定时器

app.use(express.json({ limit: "5mb" })); // 设置数据 JSON 限制为 5mb
app.use(express.urlencoded({ limit: "5mb", extended: true })); // 设置 URL 编码限制为 5mb

app.use(
    fileUpload({
        createParentPath: true,
        defParamCharset: "utf8", // 添加utf8编码
    })
);

// app.set("view engine", "ejs"); // 将ejs设置为默认的模板引擎
// app.set("views", path.resolve(__dirname, "views")); // 配置模板的路径

// CORS 配置
app.use(cors({
    origin: ['http://localhost:8080', 'http://localhost:3001', 'http://127.0.0.1:3001'],
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true // 允许携带凭证
}));

app.use("/", require("./router/index")); //路由访问控制器

// 匹配不到路由则返回404 NotFound
app.use("*", function (req, res) {
    res.header("Content-Type", "text/html;charset=utf-8");
    return res
        .status(404)
        .send(
            '<!DOCTYPE html><html><head></head><body><h1 style="text-align: center;">Page Not Found</h1></body></html>'
        );
});

app.listen(process.env.LISTEN_PORT || 3000); //监听端口

if (process.env.DEBUG_TYPE == 1) {
    //调试模式下输出信息
    console.log("启动成功：", process.env.API_DOMAIN_URL);
}
